package com.bj58.spat.dao.demo;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.bj58.sfft.utility.dao.basedao.DAOBase;
import com.bj58.sfft.utility.dao.basedao.DAOHelper;
import com.bj58.sfft.utility.dao.basedao.IPreparedStatementHandler;
import com.bj58.sfft.utility.dao.basedao.IRowCallbackHandler;
import com.bj58.spat.dao.demo.entity.User;

/**
 * 这是DAOHelper的最简单使用，对驱动包JDBC的简单封装，没有任何改动。
 * 没有ORM功能，没有防sql注入功能
 * 
 * daoHelper.execXXX 需要传入不同的callback实现，决定操作过程和返回值
 */
public class SimpleCase {
	
	static DAOHelper daoHelper;
	
	@Before
	public void init() {
		String url = SimpleCase.class.getClassLoader().getResource(".").getFile();
		try {
			daoHelper = DAOBase.createIntrance(url + "db0.properties");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@Test
	public void insert() throws Exception {
		String sql = "insert into t_user(id, uname, age) values(?, ?, ?)";
		Object result = daoHelper.execInsert(sql, new IPreparedStatementHandler() {
			public Object exec(PreparedStatement pstat) throws SQLException {
				pstat.setLong(1, 100L);
				pstat.setString(2, "zhangsan");
				pstat.setInt(3, 20);
				return pstat.executeUpdate();
			}
		});
		
		System.out.println(result);
	}
	
	@SuppressWarnings("unchecked")
	@Test
	public void select() throws Exception {
		String sql = "select * from t_user";
		List<User> users = (List<User>) daoHelper.execQuery(sql, new IRowCallbackHandler() {
			public Object exec(ResultSet resultSet) throws SQLException {
				List<User> users = new ArrayList<User>();
				
				while(resultSet.next()){
					User user = new User();
					user.setId(resultSet.getLong("id"));
					user.setUname(resultSet.getString("uname"));
					user.setAge(resultSet.getInt("age"));
					
					users.add(user);
				}
				
				return users;
			}
		});
		System.out.println(users);
	}
	
	@Test
	public void delete() throws Exception {
		String sql = "delete from t_user where id=?";
		Object result = daoHelper.execInsert(sql, new IPreparedStatementHandler() {
			public Object exec(PreparedStatement pstat) throws SQLException {
				pstat.setLong(1, 100L);
				return pstat.executeUpdate();
			}
		});
		
		System.out.println(result);
	}
	
	@After
	public void after() throws Exception {
		delete();
	}

}
